package com.example.demo.service.impl;

import com.example.demo.constant.ErrorCode;
import com.example.demo.entity.ApiResponse;
import com.example.demo.entity.AreaInfo;
import com.example.demo.exception.BaseException;
import com.example.demo.service.QueryService;
import lombok.AllArgsConstructor;
import org.springframework.cache.CacheManager;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Retryable;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;


@Service
//构造注入
@AllArgsConstructor
public class QueryServiceImpl implements QueryService {

    private final RestTemplate restTemplate;

    private final CacheManager cacheManager;

    private static final String URL = "https://cx.shouji.360.cn/phonearea.php";

    @Override
    @Retryable(
            value = {Exception.class},
            maxAttempts = 3,
            backoff = @Backoff(delay = 1000, multiplier = 2)
    )
    public AreaInfo query(String phone) {
        ApiResponse response = restTemplate.getForObject(URL + "?number=" + phone, ApiResponse.class);

        if(response == null) {
            throw new BaseException(ErrorCode.SERVER_BUSY);
        }

        if(response.getCode() != 0) {
            throw new BaseException(ErrorCode.SERVER_BUSY);
        }

        String sp=response.getData().getSp();
        cacheManager.getCache("queryHead").put(phone.substring(0,3),sp);

        return response.getData();
    }
}
